﻿#include "account.h"
#include <map>
#include <cmath>
#include<string>
#include <iomanip>
#include<vector>
double Account::total = 0;

multimap<Date, AccountRecord> Account::recordMap;
//同一个日期可以对应多个账户记录

Account::Account(const Date& date, std::string id, const string& userId)
    : id(id), balance(0), userId(userId) {
}

Account::~Account() = default;

void Account::record(Date date, double amount, const std::string& desc) {
    amount = floor(amount * 100 + 0.5) / 100;                          //保留小数点后两位
    balance += amount;
    total += amount;
    cout << date << "\t#" << id << "\t$" << amount << "\t$" << balance << "\t" << desc << endl;
    recordMap.insert(make_pair(date, AccountRecord(date, this, amount, balance, desc,userId)));

}


Date Account::getLatestDate()
{
    if (recordMap.empty())
    {
        return Date(2008, 11, 1);
    }
    auto it = recordMap.rbegin();
    return it->first;
}
double Account::getTotal() {
    return total;
}
//显示账户信息
void Account::show() const {
    cout << id << "\t余额: " << balance;
}
//查询在指定日期范围（day1 到 day2）内的所有账户记录​​
void Account::query(Date& day1, Date& day2)
{
    bool a = false;
    for (auto& it : recordMap)
    {
        if (day1 < it.first && it.first < day2)
            cout << it.first << "\t" << it.second.account->getId() << "\t" << it.second.amount << "\t"
            << it.second.balance << "\t" << it.second.desc << endl;
        a = true;
        if (!a)
        {
            cout << "在指定日期范围内没有找到记录！" << endl;
        }
    }
}
AccountRecord::AccountRecord(const Date& date, const Account* account, double amount, double balance, string desc,const string &userId)
    :date(date), account(account), amount(amount), balance(balance), desc(desc), userId(userId) 
{}

// account.cpp - 实现数据持久化方法
void Account::saveToFile(std::ofstream& file) const {
    file << id << " " << balance << " " << userId << " ";
}

Account* Account::loadFromFile(std::ifstream& file, const std::string& userId) {
    std::string id;
    double balance;
    file >> id >> balance;

    // 这是抽象方法，需要派生类实现具体逻辑
    return nullptr;
}

std::vector<AccountRecord> Account::getRecordsByDateRange(const Date& start, const Date& end) {
    std::vector<AccountRecord> result;
    for (const auto& pair : recordMap) {
        const Date& date = pair.first;
        if ( start<date && date < end) {
            result.push_back(pair.second);
        }
    }
    return result;
}